// pages/cart/index.js
import {getCartList} from '../../apis/index'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cartTotal: 0,
    goodsList: [],
    selectAll: false,
    selectedGoods: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.initData()
  },
  async initData(){
    const res = await getCartList()
    console.log('cartList', res)
    const list = res.data.list;
    const cartTotal = res.data.cartTotal;
    this.setData({
      cartTotal: cartTotal,
      goodsList: list
    })
  },
  changeSelectAll(ev){
    console.log('ev----', ev.detail)
    this.setData({
      selectAll: ev.detail
    })
    // 如果全选为true,遍历购物车列表,
    // 将所有的goods_id放到数组里
    if (ev.detail) {
       console.log(this.data.goodsList)
       let goodsList = this.data.goodsList
       let arr = []
       for(let value of goodsList){
         console.log(value)
         arr.push(value.id+'')
       }
       console.log('arr---', arr)
       this.setData({
         selectedGoods: arr
       })
    }
  },
  // 选择商品
  selectGood(ev){
    console.log(ev)
    this.setData({
      selectedGoods: ev.detail
    })
    let selectedGoods = this.data.selectedGoods
    let goodsList = this.data.goodsList
    if (selectedGoods.length < goodsList.length) {
       this.setData({
        selectAll: false
       })
    } else {
      this.setData({
        selectAll: true
       })
    }
  },
  handleOrder(){
    /*
      mode: cart
      delivery: 0
      couponId: 0
      isUsePoints: 0
      cartIds: 10010%2C10011%2C10013
    */ 
   let selectedGoods = this.data.selectedGoods
   console.log('selectedGoods', selectedGoods)
   let cartIds = encodeURIComponent(selectedGoods.join())
   console.log('cartIds===', cartIds)
   wx.navigateTo({
     url: '/pages/order/index?mode=cart&cartIds='+cartIds,
   })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})